/**
 * 
 */
package fr.fermeManager.library.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import fr.fermeManager.library.model.beans.Ferme;
import fr.fermeManager.library.utils.MybatisUtil;

/**
 * @author Mo
 * 
 */
public class DaoFermeImplDerby implements DaoFerme {
	
	
	  // uses the new MyBatis style of lookup
//	  public static void lookUpUser() throws Exception {
//	    SqlSession session = sessionFactory.openSession();
//	 
//	    try {
//	      Mapper mapper = session.getMapper(Mapper.class);
//	      User user = mapper.getUser(2);
//	      System.out.println(user.getName());  // should print out "User2"
//	 
//	    } finally {
//	      session.close();       
//	    }
//	  }
	
	private SqlSession session = MybatisUtil.getSession();

	@Override
	public List<Ferme> getAllFermes(boolean isAdmin) throws Exception {

		List<Ferme> listeFermes = new ArrayList<Ferme>();

		try {
			
			Map<String,Object> parameters = new HashMap<String, Object>();
			parameters.put("isAdmin", isAdmin);
			
			listeFermes = session.selectList("selectAllFermes",parameters);
			
		} catch (Exception e) {
			session.rollback();
			throw e;
		}

		return listeFermes;
	}

	@Override
	public void supprimerFerme(int id) throws Exception {
		try {
			
			session.delete("effacerFerme",id);
			
			session.commit();
			
		} catch (Exception e) {
			session.rollback();
			throw e;
		}
		
	}

	@Override
	public Ferme ajouterFerme(Ferme nouvelleFermeParam) throws Exception {
		
		try {
			
			if(nouvelleFermeParam.isPrincipale()){
				session.update("initiliserFermePrincipales");
			}
			
			session.insert("ajouterFerme",nouvelleFermeParam);
			
			session.commit();
			
			return nouvelleFermeParam;
			
		} catch (Exception e) {
			session.rollback();
			throw e;
		}
	}

	@Override
	public void modifierFerme(Ferme currentFerme) throws Exception {
		
		try {
			
			if(currentFerme.isPrincipale()){
				session.update("initiliserFermePrincipales");
			}
			
			session.update("modifierFerme",currentFerme);
			
			session.commit();
			
		} catch (Exception e) {
			session.rollback();
			throw e;
		}
	}

}
